﻿using System.ServiceModel.DomainServices.Client.ApplicationServices;
using Falafel.Controls.Dialogs;
using Falafel.LoginUI;
using Falafel.Services;

namespace Falafel
{
    using System.Windows;
    using System.Windows.Controls;
    using System.Windows.Navigation;
    
    public partial class MainPage
    {
        public MainPage()
        {
            InitializeComponent();
            loginContainer.Child = new LoginStatus();

            // Handle the event when the user is loaded
            ((App)Application.Current).UserLoaded += MainPage_UserLoaded;

            // Register log in and log out events
            WebContext.Current.Authentication.LoggedIn += Authentication_LoggedIn;
            WebContext.Current.Authentication.LoggedOut += Authentication_LoggedOut;

			UpdateLoginState();
        }

        void MainPage_UserLoaded(object sender, System.EventArgs e)
        {
			// Determine if the user is authenticated
			if (!WebContext.Current.User.IsAuthenticated)
			{
				// Show login dialog automatically
				LoginRegistrationWindow loginWindow = new LoginRegistrationWindow();
				loginWindow.Show();
			}
        }


        /// <summary>
        ///     After the Frame navigates, ensure the <see cref="HyperlinkButton"/> representing the current page is selected
        /// </summary>
        private void ContentFrame_Navigated(object sender, NavigationEventArgs e)
        {
            foreach (UIElement child in LinksStackPanel.Children)
            {
                HyperlinkButton hb = child as HyperlinkButton;
                if (hb != null && hb.NavigateUri != null)
                {
                    if (hb.NavigateUri.ToString().Equals(e.Uri.ToString()))
                    {
                        VisualStateManager.GoToState(hb, "ActiveLink", true);
                    }
                    else
                    {
                        VisualStateManager.GoToState(hb, "InactiveLink", true);
                    }
                }
            }
        }

        /// <summary>
        ///     If an error occurs during navigation, show an error window
        /// </summary>
        private void ContentFrame_NavigationFailed(object sender, NavigationFailedEventArgs e)
        {
            e.Handled = true;
            ExceptionDialog dlg = new ExceptionDialog(e.Exception, "Could Not Navigate To Page");
            dlg.Show();
        }

		private void Authentication_LoggedIn(object sender, AuthenticationEventArgs e)
		{
			UpdateLoginState();
			// Now logged in, Load Views
			WebContext.Current.ViewModel.LoadLookupEntities();
		}

		private void Authentication_LoggedOut(object sender, AuthenticationEventArgs e)
		{
			UpdateLoginState();

			ContentFrame.Navigate(new System.Uri("", System.UriKind.Relative));
		}

		private void UpdateLoginState()
		{
		    VisualStateManager.GoToState(this, WebContext.Current.User.IsAuthenticated ? "loggedIn" : "loggedOut", true);
		}

		private void ContentFrame_Navigating(object sender, NavigatingCancelEventArgs e)
		{
			if (!WebContext.Current.User.IsAuthenticated && !e.Uri.OriginalString.Equals("/Home"))
			{
				e.Cancel = true;
				ContentFrame.Navigate(new System.Uri("/Home", System.UriKind.Relative));
			}
		}
    }
}